Selenium Interview Questions
Selenium Interview Questions are designed to evaluate a candidate's understanding of web automation, Selenium WebDriver, locators, browser interactions, waits, alerts, frames, windows, TestNG, Page Object Model, data-driven testing, synchronization, framework design, and real-world automation practices.
Selenium WebDriver provides APIs for controlling web browsers and is commonly used with test runners such as TestNG or JUnit to organize and execute automated tests. TestNG additionally supports annotations, data-driven testing, parameters, parallel execution, configuration methods, and other features useful for automation frameworks. :contentReference[oaicite:0]{index=0}
Course Resource: Selenium Training | Register for Selenium Course Demo
1. What is Selenium?
Selenium is an open-source suite of tools and libraries used primarily for automating web browsers. Selenium WebDriver allows automation scripts to communicate with and control browsers through programming languages such as Java, Python, C#, JavaScript, Ruby, and others.
Selenium is commonly used for functional testing, regression testing, cross-browser testing, end-to-end testing, and repetitive browser automation tasks.
2. What are the Components of Selenium?
The Selenium ecosystem includes several components:
- Selenium WebDriver: Used for browser automation through programming languages.
- Selenium IDE: Browser-based record-and-playback tool.
- Selenium Grid: Used for distributed and parallel browser execution.
For modern automation frameworks, Selenium WebDriver is the primary component used to write browser automation code. :contentReference[oaicite:1]{index=1}
3. What is Selenium WebDriver?
Selenium WebDriver is an API that allows automation programs to control web browsers. It provides commands for opening URLs, locating elements, entering text, clicking elements, handling browser navigation, retrieving page information, and interacting with web applications.
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
System.out.println(driver.getTitle());
driver.quit();
4. How does Selenium WebDriver Work?
Selenium automation works by sending browser commands through the WebDriver interface to a browser-specific implementation. The browser then performs the requested operation and returns information to the automation script.
Java Test Code
|
v
Selenium WebDriver API
|
v
Browser Driver / Selenium Manager
|
v
Chrome / Firefox / Edge / Safari
|
v
Web Application
|
v
Response to Test
5. What is the Difference Between Selenium and Selenium WebDriver?
| Selenium | Selenium WebDriver |
| Umbrella project/ecosystem | Browser automation API |
| Contains multiple components | Used directly for browser automation |
| Includes WebDriver, Grid, IDE and related tools | Controls browser sessions |
6. What are the Advantages of Selenium?
- Open-source browser automation solution.
- Supports major browsers.
- Supports multiple programming languages.
- Works across operating systems.
- Can be integrated with TestNG and JUnit.
- Supports parallel and distributed execution through Selenium Grid.
- Can be integrated with Maven and CI/CD systems.
- Works well with Page Object Model and other automation design patterns.
7. What are the Limitations of Selenium?
- Selenium is primarily designed for web browser automation.
- It does not provide built-in native desktop application automation.
- It does not directly automate many native mobile application scenarios.
- Test synchronization must be designed carefully.
- Captcha and OTP automation generally should not be treated as normal UI automation targets.
- Poorly designed locators and synchronization can make tests flaky.
- Building a scalable framework requires additional libraries and framework design.
8. What is WebDriver?
WebDriver is the programming interface used to interact with web browsers. It provides methods such as get(), findElement(), click(), sendKeys(), getTitle(), and quit().
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
String title = driver.getTitle();
driver.quit();
9. What is a WebElement?
A WebElement represents an element in the web page DOM, such as a text box, button, link, checkbox, dropdown, or image.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
10. What is a Locator?
A locator is a mechanism used by Selenium to identify a web element on a page.
Common Selenium locator strategies include:
- id
- name
- className
- tagName
- linkText
- partialLinkText
- cssSelector
- XPath
driver.findElement(By.id("username"));
driver.findElement(By.name("email"));
driver.findElement(By.cssSelector("#login"));
driver.findElement(By.xpath("//button[@type='submit']"));
11. Which Locator is Generally Preferred?
When a stable and unique id is available, it is generally a good locator choice. If an id is unavailable or unstable, other strategies such as CSS selectors or XPath can be considered based on the application's DOM.
The most important consideration is not simply the locator type but whether the locator is stable, unique, readable, and maintainable.
12. What is XPath?
XPath is a query language used to locate elements within an HTML or XML document.
//input[@id='username']
Example:
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");
13. What is the Difference Between Absolute and Relative XPath?
| Absolute XPath | Relative XPath |
| Starts from the root of the document | Can start from a specific element |
| Uses a complete hierarchy | Usually shorter |
| More sensitive to DOM changes | Generally easier to maintain |
| Example: /html/body/div/form/input | Example: //input[@id='username'] |
14. What is a CSS Selector?
A CSS selector is a pattern used to identify elements using CSS-style syntax.
#username
.login-button
input[name='email']
button[type='submit']
Example:
driver.findElement(By.cssSelector("#username")).sendKeys("admin");
15. What is the Difference Between XPath and CSS Selector?
| XPath | CSS Selector |
| Uses XPath syntax | Uses CSS syntax |
| Can navigate through parent/ancestor relationships | Usually focuses on CSS-style element selection |
| Supports functions such as contains() and starts-with() | Uses CSS selector capabilities |
| Useful for complex DOM relationships | Often concise and readable |
16. What is findElement()?
findElement() searches for the first matching WebElement using the supplied locator.
WebElement element = driver.findElement(By.id("username"));
If no matching element is found, Selenium throws a NoSuchElementException.
17. What is findElements()?
findElements() returns a list of matching WebElements.
List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println(links.size());
If no matching elements are found, the method returns an empty list rather than throwing the same exception as findElement().
18. What is the Difference Between findElement() and findElements()?
| findElement() | findElements() |
| Returns one WebElement | Returns List<WebElement> |
| Returns the first matching element | Returns all matching elements |
| Throws NoSuchElementException if not found | Returns an empty list if none are found |
19. What is get()?
The get() method navigates the browser to a specified URL.
driver.get("https://example.com");
20. What is the Difference Between get() and navigate().to()?
Both can be used to navigate to a URL. The navigate() interface additionally provides browser navigation operations such as back, forward, and refresh.
driver.get("https://example.com");
driver.navigate().to("https://example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
21. What is getTitle()?
getTitle() returns the title of the current web page.
String title = driver.getTitle();
System.out.println(title);
22. What is getCurrentUrl()?
getCurrentUrl() returns the URL of the current browser page.
String url = driver.getCurrentUrl();
System.out.println(url);
23. What is close()?
close() closes the current browser window or tab controlled by the current WebDriver session.
driver.close();
24. What is quit()?
quit() terminates the WebDriver session and closes the associated browser windows.
driver.quit();
25. Difference Between close() and quit()
| close() | quit() |
| Closes the current window | Ends the WebDriver session |
| Useful when multiple windows/tabs are being managed | Normally used at the end of the test/session |
| May leave other windows open | Closes all associated browser windows |
26. What are Selenium Waits?
Waits are synchronization mechanisms used to allow automation scripts to interact with elements when the application requires time to load or become ready.
Common approaches include:
- Implicit Wait
- Explicit Wait
- Fluent Wait
27. What is Implicit Wait?
An implicit wait instructs WebDriver to wait for a specified amount of time when searching for elements before throwing a failure.
driver.manage().timeouts()
.implicitlyWait(Duration.ofSeconds(10));
It applies to element location operations throughout the WebDriver session.
28. What is Explicit Wait?
An explicit wait waits for a particular condition before continuing execution.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("loginButton")
)
);
button.click();
29. What is Fluent Wait?
Fluent Wait allows the automation framework to define a timeout, polling interval, and optionally ignored exceptions while waiting for a condition.
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
30. Which Wait Should be Preferred?
For specific dynamic conditions, explicit waits are generally preferred because they allow the test to wait for the exact condition required instead of using arbitrary delays.
For example, rather than:
Thread.sleep(5000);
Use an appropriate condition:
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("message")
)
);
31. What is Thread.sleep()?
Thread.sleep() pauses the current Java thread for a specified period.
Thread.sleep(3000);
It is generally less desirable than condition-based waits because the fixed delay may be either unnecessarily long or too short for a particular execution.
32. What is an Alert in Selenium?
A JavaScript alert is a browser dialog that must be handled separately from normal HTML elements.
Selenium provides the Alert interface.
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
33. How do you Handle Confirmation Alerts?
Alert alert = driver.switchTo().alert();
alert.accept();
To cancel the confirmation:
alert.dismiss();
34. How do you Enter Text in a Prompt Alert?
Alert alert = driver.switchTo().alert();
alert.sendKeys("Test Data");
alert.accept();
35. How do you Get Alert Text?
String message = driver.switchTo()
.alert()
.getText();
System.out.println(message);
36. What is an iframe?
An iframe is an HTML document embedded inside another HTML document. Selenium must switch into the appropriate frame before interacting with elements inside it.
37. How do you Switch to an iframe?
Selenium supports switching to a frame by index, name/id, or WebElement.
driver.switchTo().frame(0);
Using a name or id:
driver.switchTo().frame("loginFrame");
Using a WebElement:
WebElement frame =
driver.findElement(By.id("loginFrame"));
driver.switchTo().frame(frame);
38. How do you Switch Back from an iframe?
Use defaultContent() to return to the main document.
driver.switchTo().defaultContent();
Use parentFrame() when you need to move from a child frame back to its parent frame.
39. What are Browser Windows and Tabs in Selenium?
Selenium identifies browser windows and tabs using window handles. Each browser window or tab has a unique handle associated with the WebDriver session.
String mainWindow = driver.getWindowHandle();
Set<String> windows =
driver.getWindowHandles();
40. How do you Switch Between Windows?
String parent = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
}
}
41. What is the Difference Between getWindowHandle() and getWindowHandles()?
| getWindowHandle() | getWindowHandles() |
| Returns the current window handle | Returns handles of all available windows/tabs |
| Returns String | Returns Set<String> |
| Useful for identifying the current window | Useful for switching among multiple windows |
42. How do you Handle Dropdowns?
For a standard HTML select element, Selenium provides the Select class.
Select country =
new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
country.selectByValue("IN");
country.selectByIndex(2);
43. How do you Handle Checkboxes?
WebElement checkbox =
driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
44. How do you Handle Radio Buttons?
WebElement radio =
driver.findElement(By.id("male"));
if (!radio.isSelected()) {
radio.click();
}
45. What is isDisplayed()?
isDisplayed() checks whether an element is currently displayed.
boolean visible =
driver.findElement(By.id("message"))
.isDisplayed();
46. What is isEnabled()?
isEnabled() checks whether an element is enabled for interaction.
boolean enabled =
driver.findElement(By.id("submit"))
.isEnabled();
47. What is isSelected()?
isSelected() is commonly used for checkboxes, radio buttons, and selectable elements.
boolean selected =
driver.findElement(By.id("terms"))
.isSelected();
48. What is sendKeys()?
sendKeys() enters keyboard input into an editable WebElement.
driver.findElement(By.id("username"))
.sendKeys("admin");
49. What is click()?
The click() method performs a click operation on an interactable WebElement.
driver.findElement(By.id("loginButton"))
.click();
50. What is getText()?
getText() returns the visible text associated with an element.
String message =
driver.findElement(By.id("message"))
.getText();
System.out.println(message);
51. What is getAttribute()?
getAttribute() can be used to retrieve an element attribute or property value.
String value =
driver.findElement(By.id("username"))
.getAttribute("value");
52. What is JavaScriptExecutor?
JavascriptExecutor provides a way to execute JavaScript in the context of the current page.
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
element
);
It should not be used as the first solution for ordinary Selenium interactions. Prefer normal WebDriver interactions when they work reliably.
53. How do you Scroll Using JavaScript?
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"window.scrollTo(0, document.body.scrollHeight);"
);
54. What is Actions Class?
The Actions class provides higher-level user interaction operations such as mouse movement, hover, drag-and-drop, right-click, and keyboard actions.
Actions actions = new Actions(driver);
actions.moveToElement(element)
.perform();
55. How do you Perform Mouse Hover?
Actions actions = new Actions(driver);
actions.moveToElement(menu)
.perform();
56. How do you Perform Right Click?
Actions actions = new Actions(driver);
actions.contextClick(element)
.perform();
57. How do you Perform Double Click?
Actions actions = new Actions(driver);
actions.doubleClick(element)
.perform();
58. How do you Perform Drag and Drop?
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target)
.perform();
59. What is Page Object Model?
Page Object Model (POM) is a design pattern used to organize Selenium automation code by representing application pages or components as classes.
A page class normally contains:
- Page locators.
- Page-specific methods.
- Web interaction logic.
- Reusable operations related to that page.
The test class focuses on test flow while the page class manages page interaction details.
60. What are the Advantages of Page Object Model?
- Reduces duplicate Selenium code.
- Improves maintainability.
- Separates test logic from UI interaction logic.
- Makes locators easier to manage.
- Encourages reusable methods.
- Improves framework organization.
- Makes UI changes easier to manage.
61. What is PageFactory?
PageFactory is an older Selenium Java support mechanism commonly associated with initializing page object fields using annotations such as @FindBy.
public class LoginPage {
@FindBy(id = "username")
WebElement username;
@FindBy(id = "password")
WebElement password;
@FindBy(id = "loginButton")
WebElement loginButton;
}
Modern Selenium frameworks can also use direct By locators and explicit element lookup without relying on PageFactory.
62. What is TestNG?
TestNG is a testing framework for Java that provides annotations, test configuration, grouping, dependencies, parameters, data-driven testing, and execution features.
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void loginTest() {
System.out.println("Login Test");
}
}
TestNG documentation describes a test as a Java method annotated with @Test, with suite and test organization commonly configured through TestNG XML. :contentReference[oaicite:2]{index=2}
63. What are Common TestNG Annotations?
| Annotation | Purpose |
| @Test | Defines a test method |
| @BeforeMethod | Runs before each test method |
| @AfterMethod | Runs after each test method |
| @BeforeClass | Runs before methods in a class |
| @AfterClass | Runs after methods in a class |
| @BeforeTest | Runs before the configured TestNG test |
| @AfterTest | Runs after the configured TestNG test |
| @BeforeSuite | Runs before the suite |
| @AfterSuite | Runs after the suite |
| @DataProvider | Provides data-driven test data |
64. What is DataProvider in TestNG?
@DataProvider supplies multiple sets of data to a test method.
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"admin", "admin123"},
{"manager", "manager123"},
{"user", "user123"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
System.out.println(username);
}
65. What is the Difference Between @Parameters and @DataProvider?
| @Parameters | @DataProvider |
| Commonly used for configuration values | Used for multiple test data sets |
| Can receive values from testng.xml | Usually returns data from a Java method |
| Useful for browser/environment configuration | Useful for login/search/form test data |
| Does not inherently create one execution per data row | Normally creates test invocations for each data row |
66. What is testng.xml?
testng.xml is an XML configuration file used to organize TestNG suites, tests, classes, groups, parameters, and execution settings.
<suite name="RegressionSuite">
<test name="LoginTests">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
67. What is Parameterization in TestNG?
Parameterization allows configuration values to be supplied to test methods without hard-coding those values in the test implementation.
<parameter name="browser" value="chrome"/>
@Parameters("browser")
@Test
public void testBrowser(String browser) {
System.out.println(browser);
}
68. What is TestNG Dependency?
TestNG supports dependencies between test methods. A test can be configured to depend on another method or group.
@Test
public void login() {
System.out.println("Login");
}
@Test(dependsOnMethods = "login")
public void checkout() {
System.out.println("Checkout");
}
69. What is TestNG Grouping?
Groups allow related test methods to be categorized and executed together.
@Test(groups = "smoke")
public void loginTest() {
}
@Test(groups = "regression")
public void checkoutTest() {
}
70. What is Assertion in Selenium Automation?
An assertion verifies that the actual application result matches the expected result.
Assert.assertEquals(
driver.getTitle(),
"Dashboard"
);
Assertions are important because browser actions alone do not prove that the application behaved correctly.
71. What is the Difference Between Hard and Soft Assertion?
| Hard Assertion | Soft Assertion |
| Failure immediately affects the current test flow | Can collect multiple failures before final verification |
| Commonly uses Assert methods | Uses SoftAssert |
| Useful for critical checkpoints | Useful when multiple validations need to be collected |
72. What is Cross-Browser Testing?
Cross-browser testing verifies that a web application works correctly across different supported browsers.
Chrome
Firefox
Edge
Safari
Selenium WebDriver is designed to automate major browsers through their respective browser implementations. :contentReference[oaicite:3]{index=3}
73. How Can You Run Selenium Tests on Multiple Browsers?
Browser configuration can be separated from test logic using a driver factory, TestNG parameters, configuration files, or another framework-level mechanism.
if (browser.equalsIgnoreCase("chrome")) {
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("edge")) {
driver = new EdgeDriver();
}
74. What is Selenium Grid?
Selenium Grid is used to execute Selenium tests across multiple machines, browsers, or environments. It is useful when teams need distributed or parallel browser execution. :contentReference[oaicite:4]{index=4}
Test Suite
|
+---- Chrome
|
+---- Firefox
|
+---- Edge
|
+---- Different Operating Systems
75. What is Parallel Execution?
Parallel execution means running independent tests or test invocations concurrently to reduce total execution time.
TestNG supports parallel execution through its execution configuration, while Selenium Grid can distribute browser sessions across available infrastructure.
76. What is a Driver Factory?
A Driver Factory is a framework component responsible for creating and configuring WebDriver instances based on the requested browser or execution environment.
public class DriverFactory {
public static WebDriver createDriver(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
return new ChromeDriver();
}
if (browser.equalsIgnoreCase("firefox")) {
return new FirefoxDriver();
}
if (browser.equalsIgnoreCase("edge")) {
return new EdgeDriver();
}
throw new IllegalArgumentException(
"Unsupported browser: " + browser
);
}
}
77. What is ThreadLocal WebDriver?
ThreadLocal<WebDriver> can be used to maintain a separate WebDriver reference for each executing thread in a parallel automation framework.
private static ThreadLocal<WebDriver> driver =
new ThreadLocal<>();
public static void setDriver(WebDriver webDriver) {
driver.set(webDriver);
}
public static WebDriver getDriver() {
return driver.get();
}
public static void removeDriver() {
driver.remove();
}
This type of design helps prevent different parallel tests from accidentally using the same WebDriver reference.
78. What is a Selenium Automation Framework?
A Selenium automation framework is a structured collection of code, utilities, configuration, test data, page objects, reporting, test execution, and supporting components used to build maintainable automated tests.
Test Cases
|
v
Test Classes
|
v
Page Objects
|
v
Utilities / Driver Factory
|
v
Selenium WebDriver
|
v
Application
79. What is a Hybrid Automation Framework?
A hybrid framework combines multiple automation approaches and framework components. For example, it may combine Page Object Model, data-driven testing, reusable utilities, configuration management, TestNG, reporting, and external test data.
80. What is Data-Driven Testing?
Data-driven testing executes the same test logic using multiple sets of test data.
Test Logic
|
+---- Data Set 1
|
+---- Data Set 2
|
+---- Data Set 3
|
+---- Data Set 4
TestNG Data Providers are one common mechanism for implementing data-driven testing.
81. How Do You Handle Dynamic Web Elements?
Dynamic elements may have changing attributes or identifiers. Common approaches include:
- Use stable attributes where possible.
- Use carefully designed CSS selectors.
- Use XPath relationships when appropriate.
- Use explicit waits for dynamic states.
- Avoid unnecessary absolute XPath expressions.
- Work with application developers when stable test attributes are needed.
82. What is StaleElementReferenceException?
StaleElementReferenceException can occur when a previously located WebElement is no longer attached to the current DOM.
This commonly happens when the page or a portion of the DOM is refreshed or replaced.
A common solution is to locate the element again after the DOM has changed and use an appropriate wait condition.
83. What is NoSuchElementException?
This exception generally occurs when Selenium cannot locate the requested element using the supplied locator at the time the lookup is performed.
Possible causes include:
- Incorrect locator.
- Element not loaded yet.
- Wrong page.
- Element inside an iframe.
- DOM changed before lookup.
84. What is ElementClickInterceptedException?
This exception can occur when another element or overlay prevents Selenium from performing the requested click.
Possible solutions include:
- Wait until the element is clickable.
- Wait for overlays to disappear.
- Scroll the element into an appropriate position.
- Check whether another element overlaps the target.
- Use JavaScript only when appropriate and after understanding the actual UI problem.
85. What is TimeoutException?
TimeoutException can occur when a wait reaches its configured timeout without the expected condition being satisfied.
When debugging it, verify the locator, page state, synchronization strategy, application behavior, and configured timeout.
86. How Do You Capture Screenshots in Selenium?
Selenium provides the TakesScreenshot interface for capturing screenshots.
TakesScreenshot screenshot =
(TakesScreenshot) driver;
File source =
screenshot.getScreenshotAs(OutputType.FILE);
In a framework, screenshots are often captured automatically when a test fails and attached to a report.
87. What are Test Reports?
Test reports provide information about test execution, including passed tests, failed tests, skipped tests, execution duration, error details, and sometimes screenshots or other artifacts.
TestNG itself produces execution output, and automation frameworks can integrate additional reporting libraries for richer reports.
88. What is a Screenshot on Test Failure?
A screenshot on failure is an automated capture of the browser state when a test fails. It helps testers understand what was visible in the application at the time of failure.
Test Failure
|
v
Capture Screenshot
|
v
Capture Error Details
|
v
Attach to Report
|
v
Analyze Failure
89. What is Maven?
Maven is a Java build and dependency management tool. Selenium and TestNG dependencies can be declared in a Maven project so that they can be managed consistently across development and CI environments.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.x.y</version>
</dependency>
The exact Selenium version should be selected according to the project's compatibility and dependency-management requirements. Selenium's Java bindings are distributed through Maven Central. :contentReference[oaicite:5]{index=5}
90. What is CI/CD in Selenium Automation?
CI/CD allows automated tests to run as part of a software delivery pipeline. Selenium tests can be executed after code changes, during scheduled regression runs, or as part of deployment validation.
Developer Commit
|
v
CI Server
|
v
Build
|
v
Automated Tests
|
v
Selenium
|
v
Test Report
|
v
Pass / Fail Decision
91. How Do You Make Selenium Tests Maintainable?
- Use Page Object Model or another suitable abstraction.
- Create reusable utility methods.
- Use stable locators.
- Avoid duplicated browser interaction code.
- Use explicit waits for dynamic conditions.
- Separate test data from test logic.
- Centralize browser creation.
- Use meaningful naming conventions.
- Keep tests independent where possible.
- Generate useful reports and logs.
92. How Do You Reduce Flaky Selenium Tests?
- Use reliable locators.
- Use condition-based synchronization.
- Avoid unnecessary Thread.sleep().
- Keep tests independent.
- Reset application state between tests where required.
- Avoid unsafe shared WebDriver instances.
- Handle asynchronous application behavior properly.
- Use appropriate browser and environment configuration.
- Investigate failures instead of relying only on retries.
93. What is Test Retry?
Test retry means executing a failed test again according to a configured retry policy. TestNG supports retry analyzers for this purpose.
public class RetryAnalyzer
implements IRetryAnalyzer {
private int count = 0;
private static final int MAX_RETRY = 2;
@Override
public boolean retry(ITestResult result) {
if (count < MAX_RETRY) {
count++;
return true;
}
return false;
}
}
Retries should be used carefully because repeatedly rerunning a genuinely broken test can hide the underlying problem.
94. How Do You Handle Authentication in Selenium?
Authentication depends on the application architecture. Common approaches may include normal UI login, pre-authenticated browser state, API-assisted setup, cookies, or environment-specific authentication mechanisms.
The appropriate solution depends on the application's security design and test requirements.
95. Can Selenium Automate CAPTCHA?
CAPTCHA is specifically designed to distinguish automated activity from human interaction. Automated test suites should generally avoid attempting to defeat CAPTCHA.
For test environments, teams can use an approved test configuration, disable CAPTCHA in a controlled environment, or provide a test bypass according to the application's security policy.
96. Can Selenium Automate OTP?
OTP automation depends on the application's testing architecture. For controlled test environments, teams may provide test OTP mechanisms, mock services, or approved API-based setup rather than depending on real user OTP flows.
97. What is Headless Browser Execution?
Headless execution runs a browser without displaying the normal graphical browser interface.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
WebDriver driver =
new ChromeDriver(options);
Headless execution can be useful in CI environments where a visible desktop browser is unnecessary.
98. How Would You Design a Selenium Framework?
A scalable framework can separate test cases, page objects, driver management, configuration, test data, utilities, reporting, and execution configuration.
selenium-framework
|
|-- src/test/java
| |
| |-- tests
| | |-- LoginTest.java
| | |-- SearchTest.java
| | |-- CheckoutTest.java
| |
| |-- pages
| | |-- LoginPage.java
| | |-- HomePage.java
| | |-- CheckoutPage.java
| |
| |-- utilities
| | |-- DriverFactory.java
| | |-- WaitUtils.java
| | |-- ScreenshotUtils.java
| | |-- ExcelReader.java
| |
| |-- data
| |-- LoginDataProvider.java
| |-- TestData.java
|
|-- src/test/resources
| |-- config.properties
| |-- testng.xml
|
|-- pom.xml
99. Explain a Typical Selenium Test Execution Flow
TestNG Starts
|
v
Read Configuration
|
v
Create WebDriver
|
v
Open Application
|
v
Execute Test
|
v
Find Elements
|
v
Perform Actions
|
v
Validate Results
|
v
Capture Result
|
v
Generate Report
|
v
Close Browser
100. Explain a Real-World Selenium Login Test
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LoginTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com/login");
}
@Test
public void validLoginTest() {
driver.findElement(By.id("username"))
.sendKeys("admin");
driver.findElement(By.id("password"))
.sendKeys("admin123");
driver.findElement(By.id("loginButton"))
.click();
Assert.assertTrue(
driver.getTitle().contains("Dashboard")
);
}
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
In a production framework, the credentials, URL, locators, driver creation, waits, reporting, and page interactions would normally be separated into appropriate framework components.
101. Scenario-Based Interview Question: Login Button Is Not Clickable
Question: The login button is visible but Selenium cannot click it. What would you check?
- Verify the locator.
- Check whether the button is enabled.
- Check for overlays or popups.
- Check whether the element is inside an iframe.
- Scroll the element into view if required.
- Use an explicit wait for the appropriate condition.
- Investigate whether the DOM changes before the click.
102. Scenario-Based Interview Question: Element Appears After Five Seconds
Question: An element appears asynchronously after an API call. How would you automate it?
Use an explicit wait for the condition that represents readiness.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("message")
)
);
103. Scenario-Based Interview Question: Test Passes Locally but Fails in CI
Possible causes include:
- Different browser versions.
- Different screen resolution.
- Headless execution differences.
- Timing and synchronization problems.
- Environment configuration differences.
- Missing test data.
- Incorrect file paths.
- Parallel execution problems.
- Network or service dependencies.
A good debugging process compares the local and CI environment rather than simply increasing wait times.
104. Scenario-Based Interview Question: Tests Fail Only During Parallel Execution
Possible causes include shared mutable state, shared WebDriver instances, non-thread-safe utilities, shared test data, or application-level race conditions.
A framework may use isolated WebDriver instances, ThreadLocal driver management, independent test data, and thread-safe utilities where appropriate.
105. Scenario-Based Interview Question: Locator Changes Frequently
If a locator changes frequently, identify stable attributes or relationships in the DOM. A collaboration with developers may also help introduce dedicated test attributes that are stable and meaningful for automation.
106. Scenario-Based Interview Question: How Would You Automate a Data-Driven Login Test?
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"admin", "admin123"},
{"manager", "manager123"},
{"employee", "employee123"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(
String username,
String password) {
System.out.println(
"Testing: " + username
);
}
This approach keeps the test logic reusable while supplying different test-data combinations.
107. Scenario-Based Interview Question: How Would You Automate Multiple Browsers?
A common approach is to pass the browser as configuration and create the corresponding WebDriver through a Driver Factory.
Chrome
Firefox
Edge
|
v
Driver Factory
|
v
WebDriver
|
v
Same Test Logic
108. Scenario-Based Interview Question: How Would You Handle a Dynamic Table?
A dynamic table can be handled by locating rows and cells using stable relationships or attributes.
List<WebElement> rows =
driver.findElements(
By.cssSelector("table tbody tr")
);
for (WebElement row : rows) {
System.out.println(row.getText());
}
109. Scenario-Based Interview Question: How Would You Verify Every Link on a Page?
First collect the anchor elements and their URLs, then perform the required validation using an appropriate HTTP/API validation mechanism or browser navigation strategy depending on the test requirement.
List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String href = link.getAttribute("href");
System.out.println(href);
}
In a production test, the validation should also handle missing href values, redirects, authentication, and network restrictions appropriately.
110. Scenario-Based Interview Question: How Would You Handle Multiple Environments?
Environment-specific values such as application URLs, browser settings, API endpoints, and non-sensitive configuration should be separated from test logic.
QA
|
+-- URL
+-- Browser
+-- Configuration
Stage
|
+-- URL
+-- Browser
+-- Configuration
Production
|
+-- URL
+-- Browser
+-- Configuration
111. Scenario-Based Interview Question: How Would You Handle Test Data?
Small static data sets can be maintained in Java Data Providers. Larger or frequently changing data can be maintained in external sources such as CSV, Excel, JSON, databases, or test-data services.
Test Data
|
+-- DataProvider
+-- Excel
+-- CSV
+-- JSON
+-- Database
|
v
Test Method
112. Scenario-Based Interview Question: How Would You Handle a Failed Test?
A structured failure-analysis process should include:
- Read the failure message.
- Identify the failing test step.
- Review the stack trace.
- Check screenshots if available.
- Review browser logs or framework logs where relevant.
- Verify the locator and page state.
- Check synchronization.
- Determine whether the failure is an application defect, test defect, environment issue, or infrastructure issue.
- Fix the underlying cause.
- Rerun the relevant test or suite.
113. Important Selenium Interview Topics Checklist
| Topic | Interview Importance |
| Selenium WebDriver | Core browser automation |
| Locators | Element identification |
| XPath | Complex element identification |
| CSS Selectors | Efficient element identification |
| Waits | Synchronization |
| Alerts | Browser dialog handling |
| Frames | Embedded document handling |
| Windows/Tabs | Multi-window handling |
| Actions | Advanced user interactions |
| JavaScriptExecutor | JavaScript-based operations |
| TestNG | Test organization and execution |
| DataProvider | Data-driven testing |
| Page Object Model | Framework design |
| Selenium Grid | Distributed execution |
| Parallel Execution | Execution optimization |
| Reporting | Result analysis |
| Maven | Build and dependency management |
| CI/CD | Continuous automated execution |
| Exception Handling | Debugging and stability |
| Framework Design | Advanced interview discussion |
114. Selenium Interview Preparation Roadmap
- Learn Selenium fundamentals.
- Understand WebDriver architecture.
- Practice all major locator strategies.
- Master XPath and CSS selectors.
- Learn browser navigation methods.
- Practice WebElement operations.
- Understand implicit, explicit, and fluent waits.
- Practice alerts, frames, windows, and tabs.
- Learn Actions and JavaScriptExecutor.
- Learn TestNG annotations.
- Practice DataProvider and parameterization.
- Learn Page Object Model.
- Build a reusable Driver Factory.
- Learn screenshots and reporting.
- Practice Maven-based execution.
- Understand parallel execution.
- Learn Selenium Grid concepts.
- Understand CI/CD integration.
- Practice scenario-based interview questions.
- Build a complete Selenium automation framework.
115. Quick Revision Questions
- What is Selenium WebDriver?
- What are the Selenium components?
- What are Selenium locators?
- What is XPath?
- What is the difference between absolute and relative XPath?
- What is CSS Selector?
- What is the difference between findElement() and findElements()?
- What is the difference between close() and quit()?
- What are implicit and explicit waits?
- Why should Thread.sleep() generally be avoided?
- How do you handle alerts?
- How do you handle iframes?
- How do you switch between windows?
- How do you handle dropdowns?
- What is Actions class?
- What is JavaScriptExecutor?
- What is Page Object Model?
- What is TestNG?
- What is DataProvider?
- What is testng.xml?
- What is parameterization?
- What is Selenium Grid?
- What is parallel execution?
- What is ThreadLocal WebDriver?
- What is a Driver Factory?
- How do you capture screenshots?
- How do you generate test reports?
- How do you handle flaky tests?
- How do you handle dynamic elements?
- How do you design a Selenium framework?
116. Final Interview Tips
- Understand concepts instead of memorizing only definitions.
- Practice writing Selenium code without copying complete examples.
- Be comfortable explaining why a particular locator or wait strategy is used.
- Understand the difference between Selenium commands and TestNG features.
- Practice debugging common Selenium exceptions.
- Know how Page Object Model improves framework organization.
- Understand DataProvider and parameterization.
- Practice cross-browser and parallel execution concepts.
- Be prepared to explain your automation framework architecture.
- For experienced roles, prepare real-world scenarios involving flaky tests, CI/CD, reporting, test data, parallel execution, and framework maintenance.
117. Course Resources
Learn more about Selenium automation, WebDriver, testing frameworks, and practical automation skills:
118. Summary
Selenium interview preparation requires knowledge of both basic WebDriver operations and real-world automation framework concepts. Important areas include locators, XPath, CSS selectors, WebElements, browser navigation, waits, alerts, frames, windows, Actions, JavaScriptExecutor, screenshots, TestNG, DataProvider, Page Object Model, Selenium Grid, parallel execution, reporting, Maven, CI/CD, and framework architecture.
A strong Selenium candidate should also be able to troubleshoot common failures such as NoSuchElementException, StaleElementReferenceException, ElementClickInterceptedException, and TimeoutException. Practical knowledge of synchronization, stable locators, reusable framework components, test data management, and reporting is important when working on real automation projects.
Final Takeaway: Selenium interview success depends on being able to explain concepts clearly and demonstrate how those concepts are applied to real web automation problems. Practice both direct technical questions and scenario-based questions so that you can explain not only what Selenium does, but also why a particular automation approach is appropriate.